package com.chocho.producerserver.service;

import com.chocho.producerserver.bean.*;
import com.chocho.producerserver.dao.RoleDao;
import com.chocho.producerserver.dao.UserDao;
import com.chocho.producerserver.dao.UserroleDao;
import com.chocho.producerserver.utils.CacheMapUtil;
import com.chocho.producerserver.utils.JwtUtil;
import com.chocho.producerserver.utils.Msg;
import com.chocho.producerserver.utils.UUIDUtil;
import com.chocho.producerserver.vo.TokenInfo;
import com.chocho.producerserver.vo.VCollection;
import com.chocho.producerserver.vo.VUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * Created by chocho on 2022/3/20.
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserroleDao userroleDao;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserroleDao userRoleDao;
    /**
     * 登录校验
     * @param user
     * @return
     */
    public Msg login(User user){
        //将用户名、密码信息封装到Authentication类中。
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getUserPwd());

        //调用authenticate方法。
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //使用userid生成jwt，返回给前端。
        TokenInfo loginUser = (TokenInfo) authenticate.getPrincipal();
        String userid = loginUser.getUser().getUserId();
        String jwt = JwtUtil.createJWT(userid);

        //将(token，用户信息)存入自定义登录缓存中。
        Map<String, TokenInfo> cache = CacheMapUtil.getInstance();
        cache.put(userid, loginUser);

        return Msg.success().add("token", jwt);
    }

    public List<String> getRolesByUsername(String username){
        return userroleDao.selectByUsername(username);
    }

    public User selectUserById(String userId){
        return userDao.selectUserById(userId);
    }

    public User selectUserByUsername(String username){
        return userDao.selectByUsername(username);
    }

    public boolean register(VUser user){
        User u = new User();
        u.setUserPwd(user.getUserPwd());
        u.setUserName(user.getUserName());

        //生成id
        u.setUserId(UUIDUtil.getUUID());
        //密码需要使用CyptPasswordEncoder进行加密。
        u.setUserPwd(passwordEncoder.encode(user.getUserPwd()));
        //插入角色关系
        String roleId = "";
        if(user.getRole() != null && !"".equals(user.getRole())){
            if("1".equals(user.getRole())){//系统用户
                roleId = "1fc40fc1c6c84f6cb95b157d7face444";
            }else{//管理员
                roleId = "1fc40fc1c6c84f6cb95b157d7face333";
            }
        }
        UserRole userRole = new UserRole();
        userRole.setUserroleId(UUIDUtil.getUUID());
        userRole.setUserId(u.getUserId());
        userRole.setRoleId(roleId);
        userRoleDao.insert(userRole);

        return userDao.insertUser(u) > 0 ;
    }

    public List<Role> getRoleList(String userId){
        return roleDao.selectRoleByUserId(userId);
    }

    public int count(){
        return userDao.getMaxNum();
    }

    public boolean logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        TokenInfo loginUser = (TokenInfo) authentication.getPrincipal();
        String userid = loginUser.getUser().getUserId();
        //根据userid从登录缓存中删除用户信息。
        Map<String, TokenInfo> cache = CacheMapUtil.getInstance();

        return cache.remove(userid) != null;
    }

    public List<User> getUserByQuery(Map<String, Object> map){
        List<User> list = userDao.getUserByQuery(map);

        return list;
    }

    public boolean deleteUser(String ids){
        List<String> idList = new ArrayList<>();
        String []idArr = ids.split("&");
        for(int i = 0; i < idArr.length; i++){
            idList.add(idArr[i]);
        }

        return userDao.delete(idList) > 0;
    }

    public boolean updatePwd(HttpServletRequest request, String pwd){
        String token = request.getHeader("token");
        String id = CacheMapUtil.getInstance().get(token).getUser().getUserId();
        return userDao.updatePwd(id, pwd) > 0;
    }
}

